package com.springboot.dubbo.provider;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.springboot.db.entity.User;
import com.springboot.db.entity.UserExample;
import com.springboot.db.mapper.UserMapper;
import com.springboot.dubbo.param.request.QueryUserParam;
import com.springboot.dubbo.param.request.UserInParam;
import com.springboot.dubbo.param.response.UserOutParam;
import com.springboot.dubbo.service.UserService;

import io.seata.core.context.RootContext;
import lombok.extern.log4j.Log4j2;

/**
 * 用户服务类
 *
 * @author supu
 * @create 2019-01-03 18:00
 **/
@Log4j2
@Service
public class UserServiceProviderImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<UserOutParam> selectUsers(QueryUserParam param) {
        log.warn("userServiceProvider selectUsers 请求参数：{}", param);
        long start = System.currentTimeMillis();
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andIdLessThan(param.getId());
        List<User> userList = userMapper.selectByExample(example);
        log.warn("userServiceProvider selectUsers 结果：{}，查询耗时：{} ms", JSONObject.toJSONString(userList), (System.currentTimeMillis() - start));
        List<UserOutParam> userOutParamList = new ArrayList<>(userList.size());
        userList.forEach( user -> {
            UserOutParam userOutParam = new UserOutParam();
            BeanUtils.copyProperties(user, userOutParam);
            userOutParamList.add(userOutParam);
        });
        return userOutParamList;
    }

    @Override
//    @GlobalDistributedTransaction
    public void saveUsers(UserInParam param) {
        log.warn("userServiceProvider saveUsers 请求参数：{}", param);
        log.warn("开始全局事务，XID = {}", RootContext.getXID());
        User user = new User();
        BeanUtils.copyProperties(param, user);
        userMapper.insertSelective(user);
    }

    @Override
    public void updateUser(UserInParam param) {
        log.warn("userServiceProvider updateUser 请求参数：{}", param);
        log.warn("开始全局事务，XID = {}", RootContext.getXID());
        User user = new User();
        BeanUtils.copyProperties(param, user);
        userMapper.updateByPrimaryKeySelective(user);
    }
}
